"""
Author: HuWen
@file: page_environment_protection.py
@dateTime: 2025/9/4 14:22
加油加油！！！
"""
from locators.basicSecurityInformation.basicProcessInfo.loc_environmental_protection import Environmental_Protection

from common.base_page import BasePage
from common.locate_by import By
from playwright.sync_api import Page, FrameLocator
import inspect

class Environment_Protection_page(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.switch_menu("安全基础管理")
        self.switch_menu("环保档案(企业)")
        #首个lab不需要指定
        # self.check(Environmental_Protection.loc_lab_abandoned_outlet)

        # 自动生成配置列表
        self.filed_configs = self._generate_filed_configs()

    # 从page_tankmgr启发中进一步优化代码，实现配置自动装配，注意属性命名规范
    def _generate_filed_configs(self):
        """自动从Environmental_Protection类中提取元素并生成配置列表"""
        configs = []

        # 获取Environmental_Protection类的所有属性
        loc_attributes = inspect.getmembers(Environmental_Protection)

        # 筛选出以'loc_add_'开头的属性（排除类方法和特殊属性）
        for name, value in loc_attributes:
            if name.startswith('loc_add_') and isinstance(value, dict) and 'loc_role' in value:
                # 确定操作类型
                if value['loc_role'] in (By.textbox, 'textbox'):
                    action = 'fill'
                elif value['loc_role'] in (By.combobox, 'combobox'):
                    action = 'select'
                else:
                    # 跳过不需要处理的类型（如按钮等）
                    continue

                # 生成数据键名（从属性名中提取，去除前缀）
                data_key = name[len('loc_add_'):]

                # 添加到配置列表
                configs.append((action, value, data_key))

        return configs

    def create_environment(self, data: dict):
        """根据自动生成的配置列表执行创建操作"""
        self.click(Environmental_Protection.loc_add_button_abandoned)
        self.click(Environmental_Protection.loc_add_coordinate_pickup)

        self.click(Environmental_Protection.loc_add_coordinate_pickup_ok)
        self.page.wait_for_timeout(2000)


        # 遍历自动生成的配置，对每个元素执行对应操作
        for action, locator, data_key in self.filed_configs:
            value = data.get(data_key, "")
            if action == 'fill':
                self.fill(locator, value)
            elif action == 'select':
                self.select(locator, value)

        # 点击确定按钮
        self.page.wait_for_timeout(2000)

        self.click(Environmental_Protection.loc_add_ok)